<template>
  <base-breadcrumb :title="titleName">
    <searchData
      ref="searchData" 
      :search-data="searchArr"
      @search="search"
    />
    <a-card :bordered="false">
      <list-table
        ref="table"
        :columns="columns"
        :request="loadData"
        :exportConfig="{ use: true,select: $route.meta.title, all: $route.meta.title}"
        :exportPermission="{select: 'stm_005_exp_07',all: 'stm_005_expall_08'}"
        @exportAll="exportAll"
        :is-show-count-bar="false"
        @exportSelect="exportSelect" 
        @select-click="selectClick"
      >
        <template slot="prefix">
          <a-button
            v-btnPermission="'stm_005_add_01'"
            type="primary"
            class="mb12"
            icon="plus"
            @click="handlePlanOut('add')"
          >
            计划外科技成果申报
          </a-button>
        </template>
        <template slot="suffix">
          <ExcelImportButton
            v-btn-permission="'stm_005_imp_10'"
            :loading="loading"
            icon="import"
            button-text="批量导入"
            @handleSubmit="handleImport"
          />
          <export-mould
            v-btn-permission="'stm_005_dow_09'"
            style="margin-left: 5px"
            button-text="下载标准模板"
            template-code="科技成果录入标准表格.xlsx"
            icon="cloud-download"
          />
        </template>
        <template slot="bottom">
          <AuditSummary
            ref="summary"
            :form="queryParam"
            :load-count="loadCount"
            :api="api"
            :count-list="countList"
            :selectLength="selectLength" 
          />
        </template>
        <template slot="index" slot-scope="text, record, index">{{ index + 1 }}
        </template>
        <div slot="action" slot-scope="text, record">
          <MoreButton>
          <a v-btn-permission="'stm_005_loo_02'" @click="handleSee(record)">查看</a>

          <!--          <template v-if="record.isPlanOut && (record.completeStatusCode == '9' || record.completeStatusCode == 3 )">-->
          <!--            <span @click="handlePlanOut('edit', record.declareId)">编辑</span>-->
          <!--          </template>-->
          <template v-if="record.completeStatusCode == '2' || record.completeStatusCode == '7'">
            <a v-btn-permission="'stm_005_fin_04'" @click="handleComplete(record)">完成</a>
          </template>
          <template v-if="isShowSupplement(record) ">
            <a v-btn-permission="'stm_005_rep_06'" @click="handleSupplement(record)">补充</a>
          </template>
          <template v-if="record.completeStatusCode == '0' || record.completeStatusCode == 3 || record.completeStatusCode == 9">
            <a v-btn-permission="'stm_005_add_03'" @click="handleEdit(record)">申报</a>
          </template>

          <!-- 当状态为审批中,不等于待录入和草稿中 -->
          <template v-if="record.completeStatusCode != '0' && record.completeStatusCode != '9'">
            <a @click="handleAudit(record)">审批详情</a>
          </template>

          <a @click="handleDel(record)" v-if="record.completeStatusCode == '9'">删除</a>
<!--                    <span @click="handleEdit(record)">申报</span>-->
<!--                                                  <span @click="handleComplete(record)">完成</span>-->
<!--                                        <span @click="handleSupplement(record)">补充</span>-->
          </MoreButton>

        </div>
      </list-table>
    </a-card>
    <!-- 审批详情 -->
    <ApprovalDetails
      title="审批意见"
      :form="form"
      :visible.sync="visible"
      @cancel="visible = false"
    />
  </base-breadcrumb>
</template>

<script>
import {
  getDeclareCompleteList,
  getStatisticsList,
  exportAchievementsData,
  titleLabelQuery, removeDeclare, exportCompleteData, exportCompleteData2
} from '@/api/achievementsManage' 
import { getClassifyList, getGradeList } from '@/api/achievementsType'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import OrgTreeSelect from '@/components/OrgTreeSelect'
import SelectAchievementType from '@/components/Select/SelectAchievementType' // 成果分类
import SelectAchievementLevel from '@/components/Select/SelectAchievementLevel' // 成果等级
import ApprovalDetails from '@/views/science/achievementsManage/components/ApprovalDetails' // 成果等级
import AuditSummary from './components/AuditSummary'
import ExportMould from '@/components/ExportMould'

const columns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'index' },
    dataIndex: 'index',
    width: 70
  },
  {
    title: '所属分公司',
    dataIndex: 'branchCompany',
    width: 120,
    key: 'branchCompany'
  },
  {
    title: '项目名称',
    dataIndex: 'projectName',
    width: 250,
    key: 'projectName',
  },
  {
    title: '成果名称',
    width: 200,
    dataIndex: 'planAchievementsName',
    key: 'planAchievementsName'
  },
  {
    title: '成果等级',
    width: 200,
    dataIndex: 'planAchievementsLevelName',
    key: 'planAchievementsLevelName'
  },
  {
    title: '成果分类 ',
    width: 140,
    dataIndex: 'achievementType',
    key: 'achievementType'
  },
  {
    title: '获得时间',
    dataIndex: 'getAchievementsDate',
    width: 120,
    key: 'getAchievementsDate',
    customRender(text, row) {
      return row.completeStatusCode == 4 ? text : ''
    }
  },
  {
    title: '完成人',
    width: 200,
    dataIndex: 'planCompleteEmployee',
    key: 'planCompleteEmployee',
    customRender(text, row) {
      if (row.newCompleteEmployee && row.newCompleteEmployee.length) {
        return row.newCompleteEmployee.map(v => v.employeeName).join(',')
      }
      return ''
    }
  },
  {
    title: '标引',
    width: 200,
    dataIndex: 'completeIndexInfo'
  },
  {
    title: '完成状态',
    width: 120,
    dataIndex: 'completeStatusName',
    key: 'completeStatusName',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    fixed: 'right',
    width: 220,
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'a' + Date.now(),
  components: {
    ApprovalDetails,
    AuditSummary,
    ExportMould
  },
  data() {
    this.columns = columns
    return {
      loadCount: 0, // 汇总加载控件
      countList: [
        {
          title: '已选择：',
          value: 'selectLength'
        },
        {
          title: '总数：',
          value: 'total'
        },
        {
          title: '计划内待申报：',
          value: 'draftDeclareNum'
        },
        {
          title: '计划外待申报：',
          value: 'draftNum'
        },
        {
          title: '申报中：',
          value: 'submittedDeclareNum'
        },
        {
          title: '申报驳回：',
          value: 'rejectedDeclareNum'
        },
        {
          title: '申报通过：',
          value: 'declarePassNum'
        },
        {
          title: '完成审批中：',
          value: 'submittedCompleteNum'
        },
        {
          title: '完成驳回：',
          value: 'rejectedCompleteNum'
        },
        {
          title: '获得：',
          value: 'acquireNum'
        },
        {
          title: '未获得：',
          value: 'notAcquireNum'
        }
      ], //汇总列表
      api: { count: getStatisticsList },
      visible: false, // 审批详情弹窗显隐控件
      businessId: '', // 审批详情业务id
      titleName: '',
      loading: false,
      form: {},
      queryParam: {},
      loadData: (parameter) => {
        this.$refs.summary?.refresh()
        if (this.queryParam.completeIndexInfoTemp) {
          this.queryParam.completeIndexInfo = this.findTreeDataName(this.indexInfoList, this.queryParam.completeIndexInfoTemp)
        }
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return getDeclareCompleteList(requestParameters)
      },
      // branchCompanyList: [],
      achievementsTypeArr: [], //  成果分类下拉框数组，
      GradeListArr: [], //成果等级列表,
      planCompleteDate: undefined, //计划完成时间model
      completeDate: undefined, //实际完成时间model
      changeId: [], //选择统计数组id
      projectList: [],
      selectLength:0,
      searchArr: [
        // 搜索框
        {
          name: '所属单位',
          valueKey: 'searchQuery',
          type: OrgTreeSelect,
        },
        // {
        //   name: '所属分公司',
        //   valueKey: 'branchCompanyId',
        //   placeholder: '请选择',
        //   type: SelectSubCompany
        // },
        // {
        //   name: '项目名称',
        //   placeholder: '请选择',
        //   valueKey: 'projectId',
        //   type: SelectProject
        // },
        {
          name: '成果名称',
          value: 'achievementsName',
          type: 'input'
        },
        {
          name: '成果分类',
          valueKey: 'achievementsType',
          placeholder: '请选择',
          type: SelectAchievementType
        },
        {
          name: '成果等级',
          placeholder: '请选择',
          valueKey: 'achievementsLevel',
          type: SelectAchievementLevel
        },
        {
          name: '计划完成时间',
          value: 'planCompleteDate',
          type: 'date',
          attr: { valueFormat: 'YYYY-MM-DD' }
        },
        {
          name: '实际完成时间',
          value: 'completeDate',
          type: 'date',
          attr: { valueFormat: 'YYYY-MM-DD' }
        },
        {
          name: '状态',
          value: 'completeStatus',
          type: 'select',
          data: [
            { value: '0', label: '待录入' },
            { value: '1', label: '审核中' },
            { value: '2', label: '申报通过' },
            { value: '3', label: '申报驳回' },
            { value: '4', label: '获得' },
            { value: '5', label: '未获得' },
            { value: '6', label: '完成审核中' },
            { value: '7', label: '驳回' },
            { value: '8', label: '审批通过' }
          ]
        },
        {
          name: '标引',
          value: 'completeIndexInfoTemp',
          type: 'tree-select',
          attrs: {
            replaceFields: { children: 'children', title: 'name', key: 'id', value: 'id' }
          },
          data: []
        }
      ],
      delFunc: removeDeclare,
      indexInfoList: []
    }
  },
  filters: {
    statusFilter(type) {
      return statusMap[type].text
    },
    statusTypeFilter(type) {
      return statusMap[type].status
    }
  },
  created() {
    getClassifyList().then((res) => {
      this.achievementsTypeArr = res.data
    })
    this.getIndexInfoList()
  },
  methods: {
     selectClick(a,b){
      this.selectLength = a.rows.length;
    },
    async exportAll() {
      await exportCompleteData([], {}, `计划外科技成果申报.xlsx`)
    },
    async exportSelect(e) {
      this.$submitConfirm(async () => {
        await exportCompleteData(e.map(v => v.id), {}, `计划外科技成果申报.xlsx`)
      }, '只能导出状态为获得的数据！')
    },
    async getIndexInfoList() {
      this.loading = true
      let res = await titleLabelQuery()
      this.loading = false
      if (res.code === this.SUCCESS_CODE) {
        this.processTreeData(res.data)
        this.searchArr.find(item => item.value === 'completeIndexInfoTemp').data = this.indexInfoList = res.data
      }
    },
    findTreeDataName(list, id) {
      let res
      for (let i = 0; i < list.length; i++) {
        if (res) break
        let v = list[i]
        if (v.id === id) {
          res = v.name
        } else {
          if (v.children && v.children.length) {
            res = this.findTreeDataName(v.children, id)
          }
        }
      }
      return res
    },
    processTreeData(list) {
      list.map(v => {
        if (v.children && v.children.length) {
          v.selectable = false
          this.processTreeData(v.children)
          return v
        }
      })
    },
    isShowSupplement(record) {
      // return true
      // if (record.achievementType === '研发立项' || record.achievementType === '示范工程立项') return true
      // if (record.achievementType === '国家知识产权' && record.planAchievementsLevelName.includes('专利')) {
      //   return true
      // }
      if (record.completeStatusCode == '4' && record.supplement == '0') {
        if (record.completeAchievementType === '研发立项' || record.completeAchievementType === '示范工程立项') return true
        if (record.completeAchievementType === '国家知识产权' && record.completeAchievementsLevelName.includes('专利')) {
          return true
        }
      }
      return false
    },
    async handleImport(e) {
      const columns = [
        { title: '*所属分公司', dataIndex: 'branchCompany' },
        { title: '*项目名称', dataIndex: 'projectName' },
        { title: '*成果名称', dataIndex: 'declareAchievementsName' },
        { title: '*成果等级', dataIndex: 'declareAchievementsLevel' },
        { title: '*成果分类', dataIndex: 'declareAchievementsType' },
        { title: '*申报日期', dataIndex: 'declareDate' }
      ]
      let newTable = [],
        newTableTit = [],
        colEmpty = [],
        emptyTip = '',
        noneColArr = []
      e.map((row, num) => {
        let temp = {}
        newTableTit[num] = []
        for (const rowKey in row) {
          newTableTit[num].push(rowKey)

          let column = columns.find(columnRow => columnRow.title === rowKey)
          if (column) {
            try {
              let dataIndex = column.dataIndex
              temp[dataIndex] = row[rowKey]
            } catch (e) {
            }
          }
        }
        temp.settleId = this.id
        newTable.push(temp)
        //验证未填项
        let col = ['*所属分公司', '*项目名称', '*成果名称', '*成果等级', '*成果分类', '*申报日期']
        noneColArr[num] = []
        col.forEach((item, index) => {
          let status = newTableTit[num].includes(item)
          if (!status) {
            noneColArr[num].push(item)
          }
        })
        if (noneColArr[num].length > 0) {
          colEmpty[num] = {
            name: noneColArr[num],
            num: num + 1
          }
        }
      })
      if (colEmpty.length > 0) {
        for (let item in colEmpty) {
          emptyTip += '第' + colEmpty[item].num + '行：' + colEmpty[item].name + '\r\n'
        }
        emptyTip = '请完整输入内容：\r\n' + emptyTip
        this.$notification.open({ message: '提示', duration: null, description: () => <pre>{emptyTip}</pre> })
        return false
      }
      try {
        this.loading = true
        let res = await exportAchievementsData(null, { data: newTable })
        let msg = res.message
        this.loading = false
        this.$refs.table.getData(null, true)
        this.$notification.open({ message: '提示', duration: null, description: () => <pre>{msg}</pre> })
      } catch (e) {
        this.loading = false
      }
    },
    /**
     * 打开审批详情
     */
    handleAudit(e) {
      this.form = e
      this.visible = true
    },
    onSelectChange(e) {
      this.selectRowArr = e
    },
    search(val) {
      if (val) {
        this.queryParam = val
      }
      this.$refs.table.getData(null, true)
      this.loadCount++
    },
    handlePlanOut(type, id) {
      let query = {
        planRange: false,
        type: type
      }
      if (id) {
        query.id = id
      }
      this.$router.push({
        path: '/science/achievements-manage/addpost',
        query
      })
    },
    handleEdit(record) {
      let params = record
      switch (record.completeStatusCode) {
        case '0':
          params.type = '申报'
          this.$router.push({ name: 'ScienceAchievementsManageinsideDeclaration', query: params })
          break
        case '3'://申报驳回
        case '9'://草稿状态，特殊处理，不敢改让后端改了，改了又跑不起来。正常草稿状态来说应该是编辑的，但是去掉编辑了，不过还是跳编辑面面，但是页面显示的是申报
          params.type = '申报驳回'
          if (record.isPlanOut) {
            this.handlePlanOut('edit', record.declareId)
          } else {
            this.$router.push({ name: 'ScienceAchievementsManageinsideDeclaration', query: params })
          }
          break
      }
    },
    getReset() {
      this.queryParam = {}
      this.planCompleteDate = undefined
      this.completeDate = undefined
      this.Time = undefined
    },
    getClassList(typeId, value) {
      let parameter = {
        typeId: typeId
      }
      getGradeList(parameter).then((res) => {
        this.GradeListArr = res.data.data
      })
    },
    getPlanCompleteDate(data, dateString) {
      //获取计划完成时间
      this.queryParam.planCompleteDate = dateString
    },
    getCompleteDate(data, dateString) {
      //实际完成时间
      this.queryParam.completeDate = dateString
    },
    handleSee(record) {
      const query = {
        id: record.id,
        completeId: record.completeId
      }
      this.$router.push({
        name: 'ScienceAchievementsManageDetails',
        query
      })
    },
    handleDel(record) {
      this.$delList3(this.delFunc, () => {
        this.$refs.table.getData(null, true)
      }, { id: record.declareId })

    },
    handleComplete(record) {
      this.$router.push({
        name: 'ScienceAchievementsManageComplete',
        query: record
      })
    },
    //补充
    handleSupplement(record) {
      this.$router.push({
        name: 'ScienceAchievementsManageSupplement',
        query: record
      })
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    }
  }
}
</script>